from langchain_core.messages import HumanMessage
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import SecretStr

from settings import DASHSCOPE_API_KEY

# 1-定义客户端
llm = ChatOpenAI(
    model="qwen-max",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    api_key=SecretStr(DASHSCOPE_API_KEY),
    streaming=True
)

# 2-先准备一个字符串模板-单字符串模板
template = """
你是一位资深{field}专家，回答请严谨。请回答：{question}
"""
prompt_template = PromptTemplate.from_template(template)

# 3-格式输入的消息内容
chat_prompt_format = prompt_template.format(field="Python", question="print('hello')")
messages = [HumanMessage(content=chat_prompt_format)]
print("----chat_prompt_messages:", messages)

# 4-打印
print("-----Hold on, LLM 正在回答！-----")
response = llm.stream(messages)
for chunk in response:
    # 打印不换行
    print(chunk.content, end="")
